<template>
  <div>
    <top hd="搜索" />

    <van-search v-model="value" show-action placeholder="搜索宝贝标题">
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <ul>
      <li v-for="(item, i) in searchValue" :key="i" @click="onSearch(item)">
        {{ item }}
      </li>
    </ul>

   <ul class="good">
 <li v-for="(item,i) in list" :key="i">
   <img :src="'https://cube.elemecdn.com/'+item.restaurant.image_path+'.jpeg'" >
   <div class="right">
     <h4>{{item.restaurant.name}}</h4>
     <p></p>
     <p></p>
     <p></p>
   </div>
   
   </li>
</ul>
  </div>
</template>

<script>
import top from "@/components/top";
export default {
  components: { top },
  name: "search",
  data() {
    return {
      value: "",
      searchValue: [], //历史记录
      ss: [], //原始数据
      list: [], //筛选展示数据
    };
  },
  //初始化页面
  created() {
    this.searchValue = JSON.parse(localStorage.getItem("searchValue")) || [];

    // this.$axios({ url: "/list2.json", methods: "get" }).then((res) => {
    //   // console.log(res.data.items);
    //   res.data.items.forEach((item) => {
    //     console.log(item.restaurant.name);
    //   });
    // });
  },
  //事件调用时执行 结果不会缓存
  methods: {
    onSearch(obj) {
      var oldData = JSON.parse(localStorage.getItem("searchValue")) || [];
      if (oldData.length < 5) {
        this.searchValue.unshift(this.value||obj); //添加到头部一个新的
      }
      if (oldData.length == 5) {
        this.searchValue.unshift(this.value||obj);
        this.searchValue.pop(this.searchValue.length, 1); //从尾部删除一个旧的
      }
      localStorage.setItem("searchValue", JSON.stringify(this.searchValue)); //保存

      this.$axios({ url: "/list.json", methods: "get" }).then((res) => {

 //初始化解析图片url
      res.data.items.forEach((item)=>{
        item.restaurant.image_path=item.restaurant.image_path.slice(0,1)+'/'+item.restaurant.image_path.slice(1,3)+'/'+item.restaurant.image_path.slice(3,)
      })

        console.log(res.data.items);
        this.ss = res.data.items;
        if (this.ss.length != 0) {
          this.list = this.ss.filter((item, index, array) => {
            return item.restaurant.name.includes(this.value||obj);
          });
          console.log(this.list);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>

ul {
  width: 100%;
  height: 100px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;

  li {
    height: 25px;
    padding: 2px 10px;
    border-radius: 8px;
    background: pink;
  }
}

.good{
  width: 100%;
  li{
    height: 200px;
  width: 100%;
    display: flex;
    flex-wrap:wrap ;
    img{
      width: 30%;
    }
    .right{
      width: 70%;
      
    }
  }
}

</style>
